package com.ziroom.crm.mq.core.retry.policy;

import com.ziroom.crm.mq.core.retry.RetryContext;
import com.ziroom.crm.mq.core.retry.RetryPolicy;
import com.ziroom.crm.mq.core.retry.RetryType;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * <p>固定次数重试</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月08日 16:42
 * @since 1.0
 */
@Slf4j
public class CountRetryPolicy implements RetryPolicy {

    private static final long serialVersionUID = -5661639878619689652L;

    private int retryCount = 2;

    public CountRetryPolicy() {
    }

    public CountRetryPolicy(int retryCount) {
        this.retryCount = retryCount;
    }

    @Override
    public boolean canRetry(RetryContext retryContext) {
        if (Objects.isNull(retryContext.getRetryCount())) {
            return true;
        }
        //小于重试配置的消息
        return retryContext.getRetryCount() < getRetryCount();
    }

    @Override
    public RetryContext open(RetryContext parent) {
        return parent;
    }

    /**
     * 执行失败逻辑，次数等
     *
     * @param context   重试内容
     * @param exception 异常体。可空
     */
    @Override
    public void dealException(RetryContext context, Exception exception) {
        int retryCount = context.getRetryCount();
        context.setRetryCount(++retryCount);
        context.getMessage().setException(exception);

        if (context.getRetryType() == RetryType.PERSISTENCE) {
            // 持久化数量+1
            context.getMessage().setRetryCount(context.getRetryCount());
        }
    }

    /**
     * 获取重试次数
     *
     * @return 重试次数（0次，不重试）
     */
    private int getRetryCount() {
        return retryCount;
    }
}
